<?php
/**
 *
 * 版权所有：安德玛(underArmour)
 * 作    者：1554324405@qq.com
 * 日    期：2020-05-20
 * 版    本：1.0.0
 * 版本控制：
			20210119--新增会员定向推送功能
 * 功能说明：会员管理控制器。
 *
 **/
namespace Admin\Controller;

class UserController extends ComController
{
    /**
     * 首页
     */
    public function index()
    {
		$id = I('get.id','','htmlspecialchars');
        $key = I('get.keyword','','htmlspecialchars');
        $status = I('get.status','','htmlspecialchars');
        $level = I('get.level','','htmlspecialchars');
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $field = I('get.field','','htmlspecialchars');
        $sort = I('get.sort','','htmlspecialchars');
        $model = M(); 
        $sqlWhere = "1=1 and ";
        if($key){
            $sqlWhere .= "(a.username like '%{$key}%' or a.nickname like '%{$key}%'or a.password_origin like '%{$key}%') and ";
        }
        if($status){
            if($status == -1){
                $sqlWhere .= "a.`status`=0 and ";
            }
            if($status == 1){
                $sqlWhere .= "a.`status`=1 and a.expri_day >= date_format(now(),'%Y-%m-%d') and ";
            }
            if($status == 2){
                $sqlWhere .= "a.`status`=1 and a.expri_day < date_format(now(),'%Y-%m-%d') and ";
            }
        }
        if($level){
            $sqlWhere .= "a.level_id='{$level}' and ";
        }
        $sqlWhere = msubstr($sqlWhere, 0, utf8_strlen($sqlWhere) - 4, "utf-8", false);
        
        $sortSql = "a.id desc";
        if($field and $sort){
            if($field == 'son_num'){
                $sortSql = $field." ".$sort;
            }else{
                $sortSql = "a.".$field." ".$sort;
            }
            
        }
        
        $pagesize = 20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $model->query("select count(*) as total,case when a.`status`=1 and a.expri_day < date_format(now(),'%Y-%m-%d') then 2 
                                when a.`status`=0 then 0 else 1 end as active_flag,(select count(0) from dz_user b where b.pid=a.id) as son_num from
                                ".C('DB_PREFIX')."user a where ".$sqlWhere);
        $count = $count[0]['total'];
        $sql = "select a.*,case when a.`status`=1 and a.expri_day < date_format(now(),'%Y-%m-%d') then 2 
                when a.`status`=0 then 0 else 1 end as active_flag,(select count(0) from dz_user b where b.pid=a.id) as son_num from ".C('DB_PREFIX')."user a 
                where ".$sqlWhere." order by ".$sortSql." limit ".$offset . "," . $pagesize;
        $list = $model->query($sql);
        foreach ($list as $k=>&$v){
            // 会员等级
            $user_level = M('user_level')->where('id='.$v['level_id'])->find();
            $list[$k]['level_name'] = $user_level['title'];
            //提现金额
			$id = $v['id'];
			$tixian_income = M('tixian')->where(array('uid'=>$id,'status'=>2))->sum('tixian_money');
			if(!$tixian_income){
				$tixian_income = 0;
			}
			$list[$k]['tixian_income'] =$tixian_income;
			
			//任务分佣金额
			$where['uid'] = $id;
			$where['type'] = array('in','1,2,3');
			$task_income = M('user_income')->where($where)->sum('money');
			if(!$task_income){
				$task_income = 0;
			}
			$list[$k]['task_income'] =$task_income;
            // 二级推荐人数
            $tjp2 = M()->query("select count(*) as total from ".C('DB_PREFIX')."user where pid in (select id from ".C('DB_PREFIX')."user where pid='{$v['id']}')");
            $tjp2_num = $tjp2[0]['total'];
            $list[$k]['tjp2_num'] = $tjp2_num;
        }
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        // 会员等级
        $user_level_list = M('user_level')->order('o asc')->select();
        $this->assign('level_list',$user_level_list);
        $this->assign('list', $list);
        $this->assign('level_id', $level);
        $this->assign('page', $page);
        $this->assign('status',$status);
        $this->assign('p',$p);
        $this->assign('field',$field);
        $this->assign('sort',$sort);
        $this->display();  
        
    }
    
    /**
     * 导出Excel
     */
//     public function export()
//     {
//         $key = I('keyword','');
//         $status = I('status','');
//         if($key != '')
//         {
//             $where_bear['_logic'] = 'or';
//             $where_bear['nickname'] = array('like','%'.$key.'%');
//             $where_bear['username'] = array('like','%'.$key.'%');
//             $where_bear['mobile'] = array('like','%'.$key.'%');
//             $where_bear['real_name'] = array('like','%'.$key.'%');
//         }
        
//         if($key != ''){
//             $where_final['_complex'] = $where_bear;
//         }
        
//         if($status != '')
//         {
            
//             $where_final['status'] = $status;
//         }
        
//         $m = M('user');
//         $list = $m->order('id desc')->where($where_final)->Field('username,nickname,mobile,sex,status,city,t,login_t')->select();
//         foreach ($list as $key => &$value)
//         {
//             if($list[$key]['sex'] == 1){
//                 $list[$key]['sex'] = '男';
//             }else{
//                 $list[$key]['sex'] = '女';
//             }
//             if($list[$key]['status'] == 1){
//                 $list[$key]['status'] = '正常';
//             }else{
//                 $list[$key]['status'] = '禁止';
//             }
//             $list[$key]['t'] = date( "Y-m-d H:i",$list[$key]['t']);
//             $list[$key]['login_t'] = date( "Y-m-d H:i",$list[$key]['login_t']);
            
//             $list[$key]['mobile'] = ' '.$list[$key]['mobile'];
//             $list[$key]['username'] = ' '.$list[$key]['username'];
//         }
//         $xlsName  = "User_".$_SESSION['uid'].date('_YmdHis');
//         $xlsCell  = array(
//             array('username','用户名'),
//             array('nickname','昵称'),
//             array('sex','性别'),
//             array('mobile','手机号'),
//             array('city','地区'),
//             array('status','状态'),
//             array('t','注册时间'),
//             array('login_t','最近登录')
//         );
//         $this->exportExcel($xlsName, $xlsCell, $list);
        
//     }
    
    /**
     * 会员禁止
     */
    public function ban(){
        $id = I('id');
        $status = I('status');
        $p = I('p',1);
        if(!$id)
        {
            $this->error('传参为空');
        }
        if($status == '')
        {
            $this->error('状态值为空');
        }
        
        $res = M('user')->where('id='.$id)->save(array('status'=>$status));
        if($res){
            if($status == 1) {
                $log = '启用';
            }else{
                $log = '禁止';
            }
            addlog($log.'会员成功，会员ID：'.$id);
            $this->redirect(U('index',array('p'=>$p)));
        }else{
            $this->error('操作失败！');
        }
    }
    
    
    
    /**
     * 删除
     */
    public function delete()
    {
        
        $id = I('id');
        if(!$id){
            $this->error('传参为空');
        }
        $model = M('user');
        //$model2 = M('user_token');
        
        //$model1->startTrans();
        
        $res = $model->where('id='.$id)->delete();
        //$res2 = $model2->where('uid='.$id)->delete();
        
        
        if($res){
            M('user_token')->where('uid='.$id)->delete();
            addlog('会员删除成功，会员ID：'.$id);
            $this->success('会员删除成功',U('index'));
        }else{
            $this->error('操作错误');
        }
        
    }
    
    
    /**
     * 修改会员等级
     */
    public function updateLevel()
    {
        $uid = I('uid');
        if(!$uid){
            $this->error('传参为空');
        }
        if(IS_POST){
            $level_id = I('post.level_id','','htmlspecialchars');
            // 计算该等级有效天数
            $level_info = M('user_level')->where('id='.$level_id)->field('expri_day,title')->find();
            $days = intval($level_info['expri_day']);
            $data = array(
                'level_id'=>$level_id,
                'expri_day'=>date("Y-m-d",strtotime("$days day"))
            );
            //更新数据库
            $res = M('user')->data($data)->where('id='.$uid)->save();
            if($res){
                addlog('修改会员等级，ID：' . $uid);
                //$this->success('操作成功！',U('updateLevel',array('uid'=>$uid,'close'=>1)));
                redirect(U('updateLevel',array('uid'=>$uid,'close'=>1)));
                die(0);
            }else {
                $this->error('发生异常');
            }
        }else{
            $user_level_list = M('user_level')->order('o asc')->select();
            $user_level = M('user')->where('id='.$uid)->field('level_id')->find();
            $this->assign('user_level_list',$user_level_list);
            $this->assign('level_id',$user_level['level_id']);
            $this->assign('uid',$uid);
            $this->display('form');
        }
    }
    

/**
     * 会员推送
     */
    public function updateMessage()
    {
        $uid = I('uid');
        if(!$uid){
            $this->error('传参为空');
        }
       if(IS_POST){
           $message_id = I('post.message_id','','htmlspecialchars');
           $message_info = M('message')->where('id='.$message_id)->field('title,pic')->find();
		   $user_info = M('user')->where('id='.$uid)->field('username')->find();
           $data = array(
               'pic'=>$message_info['pic'],
			   'show_ts'=>1
           );
           //更新数据库
           $res = M('user')->data($data)->where('id='.$uid)->save();
           if($res){
			   $username = $user_info['username'];
			   $title = $message_info['title'];
               // addlog('推送成功!!推送人手机：' . $username);
			   addlog('推送"'.$title.'"成功！推送人手机号：'. $username);
               //$this->success('操作成功！',U('updateLevel',array('uid'=>$uid,'close'=>1)));
               redirect(U('updateMessage',array('uid'=>$uid,'close'=>1)));
               die(0);
            }else {
                $this->error('发生异常');
            }
        }else{
            $message_list = M('message')->select();
            $user_level = M('user')->where('id='.$uid)->field('level_id')->find();
            $this->assign('message_list',$message_list);
            $this->assign('uid',$uid);
            $this->display('form1');
        }
    }
}